Page({
  data: {
    status: 'LED is ON!',
    deviceName: '',
    deviceId: '',
    serviceId: '',
    characteristicId: ''
  },

  onLoad: function(options) {
    wx.showLoading({
      title: '请打开蓝牙',
    });
    this.setData({
      deviceName: options.id,// 设备名
    });
    var that = this

    var deviceName = options.id
    wx.closeBluetoothAdapter({
      success: function(res) {
        // 初始化蓝牙适配器
        wx.openBluetoothAdapter({
          success: function(res) {
            wx.hideLoading()
            wx.showLoading({
              title: '请稍后....',
            });
            wx.startBluetoothDevicesDiscovery({
              allowDuplicatesKey: false,
              success: function(res) {
                // 添加延迟
                setTimeout(() => {
                  wx.getBluetoothDevices({
                    success: function(res) {
                      for (var i = 0; i < res.devices.length; i++) {
                        if (res.devices[i].name == deviceName) {
                          that.setData({// 获取deviceID
                            deviceId: res.devices[i].deviceId,
                          })
                          wx.hideLoading()
                          wx.showLoading({
                            title: '正在连接...',
                          });
                          that.CreateBLEConnection()
                        }
                      }
                    },
                    fail: function() {
                      console.log("搜索蓝牙设备失败")
                    }
                  });
                }, 1000);
              },
            });
          },
        })
      }
    });
  },
  // 连接蓝牙
  CreateBLEConnection: function() {   
    var that = this;
    // 在连接蓝牙前需要先stop，微信的设定
    wx.stopBluetoothDevicesDiscovery({
      success: function(res) {
        console.log('停止搜索设备', res)
      }
    })
    wx.createBLEConnection({
      deviceId: that.data.deviceId,
      success: function(res) {
        wx.hideLoading();
        // 获取设备的服务UUID
        wx.getBLEDeviceServices({
          deviceId: that.data.deviceId,
          success: function(service) {
            var all_UUID = service.services; // 取出所有的服务
            var UUID_lenght = all_UUID.length; // 获取服务数组的长度
            // 遍历服务数组
            for (var index = 0; index < UUID_lenght; index++) {
              var ergodic_UUID = all_UUID[index].uuid; // 取出服务里面的UUID
              var UUID_slice = ergodic_UUID.slice(4, 8); // 截取4到8位
              // 判断是否是我们需要的服务，ESP32服务设定为0001
              if (UUID_slice == '0001') {
                var index_uuid = index;
                that.setData({
                  serviceId: all_UUID[index_uuid].uuid // 确定需要的服务UUID
                });
              };
            };
            that.Characteristics(); //调用获取特征值函数
          },
        });
      },
    })
  },
  Characteristics: function() {
    var that = this;
    var device_characteristics = [];
    var characteristics_uuid = {};
    wx.getBLEDeviceCharacteristics({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      success: function(res) {
        // 获取到所有特征值
        var characteristics = res.characteristics; 
        //获取到特征值数组的长度
        var characteristics_length = characteristics.length; 
        // 遍历获取到的characteristicsId
        for (var index = 0; index < characteristics_length; index++) {
          // 取出特征值里面的UUID
          var characteristics_UUID = characteristics[index].uuid; 
          // 截取4到8位
          var characteristics_slice = characteristics_UUID.slice(4, 8); 
          // 判断是否是我们需要的0002 WRITE服务
          if (characteristics_slice == '0002') {
            var index_uuid = index;
            that.setData({// 确定的写入UUID
              characteristicsId: characteristics[index_uuid].uuid 
            });
            lightoff()
            lighton()
          }
        };
      },
    })
  },
  
  lightoff: function() {
    var that = this;
    var value_ascii = "";
    var value_initial = "LED_OFF"; 
    // 将字符一个一个分开
    var value_split = value_initial.split('');
    for (var i = 0; i < value_split.length; i++) {
      //转为Ascii字符后连接
      value_ascii = value_ascii + value_split[i].charCodeAt().toString(16); 
    }
    var value = value_ascii;
    //调用数据发送函数
    var write_function = that.write(value); 
  },

  lighton: function() {
    var that = this;
    var value_ascii = "";
    var value_initial = "LED_ON";
    // 将字符一个一个分开
    var value_split = value_initial.split(''); 
    for (var i = 0; i < value_split.length; i++) {
      // 转为Ascii字符后连接
      value_ascii = value_ascii + value_split[i].charCodeAt().toString(16); 
    }
    var value = value_ascii;
    // 调用数据发送函数
    var write_function = that.write(value); 
  },

  write: function(str) {
    var that = this;
    var value = str;
    // 将数值转为ArrayBuffer类型数据
    var typedArray = new Uint8Array(value.match(/[\da-f]{2}/gi).map(function(h) {
      return parseInt(h, 16)
    }));
    var buffer = typedArray.buffer;
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.characteristicsId,
      value: buffer,
      });
    },

  onUnload: function() {
    var that = this;
    wx.closeBLEConnection({
      deviceId: that.data.deviceId,
      success: function(res) {
        console.log('断开设备连接', res);
      }
    });
  },
})